package curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2017/3/13.
 */
public class ZkCurator {

    private static final String ZK_ADDR = "127.0.0.1:2181" ;
    private static final int TIME_OUT_MS = 500000 ;

    public static void main (String[] args)throws Exception{
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(ZK_ADDR, retryPolicy);
        client.start();

        client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/path/ZHANG", "sssssssss".getBytes());
        System.out.println(new String(client.getData().forPath("/path/ZHANG")));

        client.setData().forPath("/path/ZHANG","AAAAAAAAA".getBytes());
        System.out.println(new String(client.getData().forPath("/path/ZHANG")));

        //多线程，并支持回调函数
        ExecutorService pool = Executors.newFixedThreadPool(2);
        client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework cf, CuratorEvent ce) throws Exception {
                        System.out.println("code:" + ce.getResultCode());
                        System.out.println("type:" + ce.getType());
                        System.out.println("线程为:" + Thread.currentThread().getName());
                    }
                }, pool)
                .forPath("/super/c3","c3内容".getBytes());
        Thread.sleep(Integer.MAX_VALUE);


        // 读取子节点getChildren方法 和 判断节点是否存在checkExists方法
        /**
         List<String> list = cf.getChildren().forPath("/super");
         for(String p : list){
         System.out.println(p);
         }

         Stat stat = cf.checkExists().forPath("/super/c3");
         System.out.println(stat);

         Thread.sleep(2000);
         cf.delete().guaranteed().deletingChildrenIfNeeded().forPath("/super");
         */


        //cf.delete().guaranteed().deletingChildrenIfNeeded().forPath("/super");
    }
}
